package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

   @Autowired
    private SetmealService setmealService;
   @Autowired
    private SetmealDishService setmealDishService;
   @Autowired
   private CategoryService categoryService;

   @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto){
       log.info("套餐信息：{}",setmealDto);

       setmealService.saveWithDish(setmealDto);

       return R.success("添加套餐成功");
   }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        //构建分页条件
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据name进行like模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);
        //添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo,queryWrapper);

        //参考DishController菜品信息分页查询
        Page<SetmealDto> setmealDtoPage = new Page<>(page, pageSize);

        ArrayList<SetmealDto> setmealDtos = new ArrayList<>();

        List<Setmeal> setmeals = pageInfo.getRecords();
        for (Setmeal setmeal : setmeals) {
            SetmealDto setmealDto = new SetmealDto();

            BeanUtils.copyProperties(setmeal,setmealDto);

            Long categoryId = setmeal.getCategoryId();

            Category categoryForName = categoryService.getById(categoryId);
            setmealDto.setCategoryName(categoryForName.getName());

            setmealDtos.add(setmealDto);
        }
        //将setmealDto的集合，放入到page<setmealDto>中，作为分页数据
        setmealDtoPage.setRecords(setmealDtos);

        return R.success(setmealDtoPage);
    }



    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("ids：{}",ids);

        setmealService.deleteWithSetmealDish(ids);

        return R.success("删除套餐成功");
    }
}
